from flask import Flask, Blueprint
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
import os
import importlib
from config import *

db = SQLAlchemy()   # 数据库对象 ORM映射
migrate = Migrate()  # 数据库迁移 
 
 
def init_database(app):    # 函数作用与app实例绑定
    if IS_SQLLITE3:
        db_path = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'database.db')
        app.config['SQLALCHEMY_DATABASE_URI'] = f'sqlite:///{db_path}'
    else:
        app.config['SQLALCHEMY_DATABASE_URI'] = f'postgresql://{USER}:{PWD}@{HOST}:{PORT}/{DATABASE}'
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
    db.init_app(app)
    migrate.init_app(app, db)

# 首先创建db实例，但不要立即初始化
def create_app(is_cli=False):
    app = Flask(__name__)

    # 初始化db
    init_database(app)
    if is_cli:
        return app
    
    # 创建所有表
    with app.app_context():
        db.create_all()
        
    # 自动注册蓝图
    register_blueprints(app)

    # 自动注册中间件
    register_middleware(app)
    return app

def register_blueprints(app):
    # 获取apps目录的绝对路径
    apps_dir = os.path.dirname(os.path.abspath(__file__))
    
    # 遍历apps目录下的所有文件夹
    for module_name in os.listdir(apps_dir):
        module_path = os.path.join(apps_dir, module_name)
        
        # 确保是目录且不是以下划线开头（排除 __pycache__ 等）
        if os.path.isdir(module_path) and not module_name.startswith('_'):
            try:
                # 动态导入模块（例如：apps.users）
                module = importlib.import_module(f'apps.{module_name}')
                
                # 查找模块中的蓝图对象（通常命名为 blue 或 blueprint）
                for attr_name in dir(module):
                    attr = getattr(module, attr_name)
                    if isinstance(attr, Blueprint):
                        # 注册找到的蓝图
                        app.register_blueprint(attr)
                        print(f'成功注册蓝图: {module_name} - {attr.name}')
            except Exception as e:
                print(f'注册蓝图 {module_name} 时出错: {str(e)}')

def register_middleware(app):
    try:
        module = importlib.import_module(f'common.middleware')
        for attr_name in dir(module):
            attr = getattr(module, attr_name)
            if attr_name.endswith("Middleware"):
                app.wsgi_app = attr(app.wsgi_app)
                print(f'成功注册中间件:  - {attr_name}')
    except Exception as e:
        print(f'注册中间件时出错: {str(e)}')
